<?php

/**
 * This is the model class for table "leaves".
 *
 * The followings are the available columns in table 'leaves':
 * @property integer $id
 * @property integer $employeeId
 * @property string $name
 * @property string $start
 * @property integer $debit
 * @property integer $balance
 * @property string $note
 * @property string $status
 * @property string $createdAt
 * @property string $updatedAt
 * @property integer $createdBy
 * @property integer $updatedBy
 */
class Leave extends ActiveRecordUser {

	const NAME_ANNUALY = 'Annualy';
	const NAME_CONDOLENCE = 'Condolence';
	const NAME_MATERNITY = 'Baby born';
	const NAME_MARRIAGE = 'Marriage';
	const NAME_SICK = 'Sick';
	const NAME_FAMILY_MATTER = 'Family Matter';
	const NAME_OTHER = 'Other';
	const STATUS_PENDING = 'Pending';
	const STATUS_REJECTED_SUPERVISOR = 'Rejected Supervisor';
	const STATUS_REJECTED_MANAGEMENT = 'Rejected Management';
	const STATUS_APPROVED_SUPERVISOR = 'Approved Supervisor';
	const STATUS_APPROVED_MANAGEMENT = 'Approved Management';
	const STATUS_CANCELED = 'Canceled';

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Leave the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'leaves';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		return array(
			array(
				'employeeId, name, status',
				'required',
				'on'=>'insert, update',
			),
			array(
				'employeeId',
				'required',
				'on'=>'mass',
			),
			array(
				'debit',
				'numerical',
				'on'=>'insert, update, request, mass',
				'allowEmpty'=>false,
				'integerOnly'=>true,
				'min'=>1,
			),
			array(
				'balance',
				'numerical',
				'on'=>'insert, update, request',
				'allowEmpty'=>false,
				'integerOnly'=>true,
				'min'=>0,
			),
			array(
				'start',
				'date',
				'on'=>'insert, update, request, mass',
				'allowEmpty'=>false,
				'format'=>'yyyy-MM-dd',
			),
			array(
				'status',
				'uniquePending',
				'on'=>'insert, update, request',
			),
			array(
				'start',
				'uniqueDate',
				'on'=>'insert, update, request',
			),
			array(
				'start',
				'banWeekend',
				'on'=>'insert, update, request',
			),
			array(
				'start',
				'unique',
				'on'=>'insert, update, request',
				'className'=>'Holiday',
				'attributeName'=>'date',
				'message'=>'{value} is holiday',
			),
			array(
				'note',
				'safe',
				'on'=>'insert, update, request, mass',
			),
			array(
				'id, employeeId, name, start, debit, balance, status, note',
				'safe',
				'on'=>'search'
			),
		);
	}

	public function uniquePending($attribute, $params) {
		$data = array(
			'condition'=>'employeeId = :employeeId AND status = :status',
			'params'=>array(
				':employeeId'=>$this->employeeId,
				':status'=>self::STATUS_PENDING,
			),
		);
		$criteria = new CDbCriteria($data);
		$leave = self::model()->find($criteria);
		if ($leave && $leave->id != $this->id) {
			$s = 'The employee already have pending leave request';
			$this->addError($this->employeeId, $s);
		}
	}

	public function uniqueDate($attribute, $params) {
		if (!$this->$attribute) return;

		$data = array(
			'condition'=>'employeeId = :employeeId AND start = :start',
			'params'=>array(
				':employeeId'=>$this->employeeId,
				':start'=>$this->$attribute,
			),
		);
		$criteria = new CDbCriteria($data);
		$leave = self::model()->find($criteria);
		if ($leave && $leave->id != $this->id) {
			$s = 'The employee already have leave on this date';
			$this->addError($attribute, $s);
		}
	}
	
	public function banWeekend($attribute, $params) {
		if (!$this->$attribute) return;

		$timestamp = CDateTimeParser::parse($this->$attribute, 'yyyy-MM-dd');
		$weekday = date('N', $timestamp);
		if ($weekday >= 6) {
			$s = $this->$attribute . ' is weekend';
			$this->addError($attribute, $s);
		}
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'employee'=>array(self::BELONGS_TO, 'Employee', 'employeeId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id'=>'ID',
			'employeeId'=>'Employee',
			'employee.name'=>'Employee',
			'name'=>'Reason',
			'start'=>'Starting',
			'debit'=>'Total Days',
			'balance'=>'Balance',
			'note'=>'Note',
			'employee.supervisor.name'=>'Supervisor',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;
		$criteria->order = 'start DESC';

		$criteria->compare('id', $this->id);
		$criteria->compare('employeeId', $this->employeeId);
		$criteria->compare('name', $this->name, true);
		$criteria->compare('start', $this->start, true);
		$criteria->compare('debit', $this->debit);
		$criteria->compare('balance', $this->balance);
		$criteria->compare('note', $this->note, true);
		$criteria->compare('status', $this->status, false);

		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
			));
	}

	public function sendRequestSupervisorNotification() {
		$supervisor = $this->employee->supervisor;
		if (!$supervisor) return;

		$email = $this->employee->supervisor->email;
		if (!$email) return;

		$subject = Yii::app()->name . ': New Leave Request';
		$name = $this->employee->name;
		$position = $this->employee->position;
		$division = $this->employee->division;
		$group = $this->employee->group;
		$plural = $this->debit > 1 ? 's' : '';
		$start = Yii::app()->format->formatDate($this->unixStart);
		$href = Yii::app()->request->hostInfo;
		$href .= CHtml::normalizeUrl(array('leave/approve', 'id'=>$this->id));
		$approve = "<a target=\"_blank\" href=\"{$href}\">";
		$href .= CHtml::normalizeUrl(array('leave/reject', 'id'=>$this->id));
		$reject = "<a target=\"_blank\" href=\"{$href}\">";
		$balance = $this->employee->leaveBalance;
		$message = "
            <html>
            <head>
                <title>
                    New Leave Request
                </title>
            </head>
            <body>
                <p>
					Name: {$name}<br />
					Position: {$position}<br />
					Division: {$division}<br />
					Group: {$group}
				</p>
				<p>
					Requesting a leave of absence for {$this->debit}
					day{$plural} starting from {$start}.
				</p>
				<p>
					Current leave balance is {$balance},
					after is {$this->balance}.
				</p>
				<p>Click {$approve}here</a> to approve.</p>
				<p>Click {$reject}here</a> to reject.</p>
            </body>
            </html>
            ";
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$from = Yii::app()->params['admin']['email'];
		$headers .= "From: $from\r\n";
		$headers .= "Reply-To: $from";
		mail($email, $subject, $message, $headers);
	}

	public function sendRequestManagementNotificaton() {
		$condition = 'isManagement = :isManagement';
		$params = array(':isManagement'=>true);
		$managements = Employee::model()->findAll($condition, $params);
		if (!$managements) return;

		$emails = array();
		foreach ($managements as $management) {
			if ($management->email) {
				$emails[] = $management->email;
			}
		}
		if (!$emails) return;

		$subject = Yii::app()->name . ': New Leave Request';
		$name = $this->employee->name;
		$position = $this->employee->position;
		$division = $this->employee->division;
		$group = $this->employee->group;
		$plural = $this->debit > 1 ? 's' : '';
		$start = Yii::app()->format->formatDate($this->unixStart);
		$href = Yii::app()->request->hostInfo;
		$href .= CHtml::normalizeUrl(array('leave/consent', 'id'=>$this->id));
		$approve = "<a target=\"_blank\" href=\"{$href}\">";
		$href .= CHtml::normalizeUrl(array('leave/negate', 'id'=>$this->id));
		$reject = "<a target=\"_blank\" href=\"{$href}\">";
		$balance = $this->employee->leaveBalance;
		$message = "
            <html>
            <head>
                <title>
                    New Leave Request
                </title>
            </head>
            <body>
                <p>
					Name: {$name}<br />
					Position: {$position}<br />
					Division: {$division}<br />
					Group: {$group}
				</p>
				<p>
					Requesting a leave of absence for {$this->debit}
					day{$plural} starting from {$start}.
				</p>
				<p>
					Current leave balance is {$balance},
					after is {$this->balance}.
				</p>
				<p>Click {$approve}here</a> to approve.</p>
				<p>Click {$reject}here</a> to reject.</p>
            </body>
            </html>
            ";
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$from = Yii::app()->params['admin']['email'];
		$headers .= "From: $from\r\n";
		$headers .= "Reply-To: $from";
		$email = implode(', ', $emails);
		mail($email, $subject, $message, $headers);
	}

	public function sendApprovalNotificaton() {
		if (!$this->employee->email) return;

		$subject = Yii::app()->name . ': Leave Request Approval Notification';
		$plural = $this->debit > 1 ? 's' : '';
		$start = Yii::app()->format->formatDate($this->unixStart);
		$href = Yii::app()->request->hostInfo;
		$href .= CHtml::normalizeUrl(array('leave/consent', 'id'=>$this->id));
		$balance = $this->employee->leaveBalance;
		$message = "
            <html>
            <head>
                <title>
                    Leave Request Approval
                </title>
            </head>
            <body>
				<h1>Congratulations</h1>
                <p>
					Your leave request for {$this->debit} day{$plural} starting
					{$start} has been approved by supervisor and now waiting for
					management consent.
				</p>
            </body>
            </html>
            ";
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$from = Yii::app()->params['admin']['email'];
		$headers .= "From: $from\r\n";
		$headers .= "Reply-To: $from";
		mail($this->employee->email, $subject, $message, $headers);
	}

	public function sendConsentNotification() {
		if (!$this->employee->email) return;

		$subject = Yii::app()->name . ': Leave Request Consent Notification';
		$plural = $this->debit > 1 ? 's' : '';
		$start = Yii::app()->format->formatDate($this->unixStart);
		$href = Yii::app()->request->hostInfo;
		$href .= CHtml::normalizeUrl(array('leave/consent', 'id'=>$this->id));
		$balance = $this->employee->leaveBalance;
		$message = "
            <html>
            <head>
                <title>
                    Leave Request Approval
                </title>
            </head>
            <body>
				<h1>Congratulations</h1>
                <p>
					Your leave request for {$this->debit} day{$plural} starting
					{$start} has been consented by management.
				</p>
				<p>
					Your leave balance now is {$balance}.
				</p>
            </body>
            </html>
            ";
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$from = Yii::app()->params['admin']['email'];
		$headers .= "From: $from\r\n";
		$headers .= "Reply-To: $from";
		mail($this->employee->email, $subject, $message, $headers);
	}

	public function sendRejectionNotificaton() {
		if (!$this->employee->email) return;

		$subject = Yii::app()->name . ': Leave Request Rejection Notification';
		$plural = $this->debit > 1 ? 's' : '';
		$start = Yii::app()->format->formatDate($this->unixStart);
		$href = Yii::app()->request->hostInfo;
		$href .= CHtml::normalizeUrl(array('leave/consent', 'id'=>$this->id));
		$rejector = 'Supervisor';
		if ($this->status == Leave::STATUS_REJECTED_MANAGEMENT) {
			$rejector = 'Management';
		}
		$message = "
            <html>
            <head>
                <title>
                    Leave Request Approval
                </title>
            </head>
            <body>
				<h1>Sorry</h1>
                <p>
					Your leave request for {$this->debit} day{$plural} starting
					{$start} has been rejected by {$rejector}.
				</p>
            </body>
            </html>
            ";
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$from = Yii::app()->params['admin']['email'];
		$headers .= "From: $from\r\n";
		$headers .= "Reply-To: $from";
		mail($this->employee->email, $subject, $message, $headers);
	}

	public function getMenu($action, $toolbar = false) {
		$tool = Yii::app()->request->baseUrl . '/images/toolbars';
		$name = 'Leave';
		$user = Yii::app()->user;
		$menu = array();

		$label = "View $name";
		if ($toolbar) $label = "<img src=\"$tool/magnifier-left.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array('view', 'id'=>$this->id),
			'visible'=>$action != 'view' && $user->checkAccess('Leave.View'),
			'linkOptions'=>array('title'=>'View'),
		);

		$label = "Update $name";
		if ($toolbar) $label = "<img src=\"$tool/pencil.png\" />";
		$visible = $action != 'update' && $user->checkAccess('Leave.Update');
		$menu[] = array(
			'label'=>$label,
			'url'=>array('update', 'id'=>$this->id),
			'visible'=>$visible,
			'linkOptions'=>array('title'=>'Update'),
		);

		$label = "Delete $name";
		if ($toolbar) $label = "<img src=\"$tool/cross-script.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>'#',
			'visible'=>$user->checkAccess('Leave.Delete'),
			'linkOptions'=>array(
				'submit'=>array('delete', 'id'=>$this->id),
				'confirm'=>'Are you sure you want to delete this item?',
				'title'=>'Delete',
			)
		);

		$label = "Approve $name";
		if ($toolbar) $label = "<img src=\"$tool/tick-shield.png\" />";

		if ($this->status == self::STATUS_PENDING) {
			$visible = $action != 'approve' &&
				$user->checkAccess('Leave.Approve');
			$menu[] = array(
				'label'=>$label,
				'url'=>array('approve', 'id'=>$this->id),
				'visible'=>$visible,
				'linkOptions'=>array('title'=>'Approve'),
			);

			$label = "Reject $name";
			if ($toolbar) $label = "<img src=\"$tool/cross-shield.png\" />";
			$visible = $action != 'reject' &&
				$user->checkAccess('Leave.Reject');
			$menu[] = array(
				'label'=>$label,
				'url'=>array('reject', 'id'=>$this->id),
				'visible'=>$visible,
				'linkOptions'=>array('title'=>'Reject'),
			);

			$label = "Cancel $name";
			if ($toolbar) {
				$label = "<img src=\"$tool/arrow-curve-180-left.png\" />";
			}
			$visible = $action != 'cancel' &&
				($user->isSuperuser ||
				($user->employee && $this->employeeId == $user->employee->id));
			$menu[] = array(
				'label'=>$label,
				'url'=>array('cancel', 'id'=>$this->id),
				'visible'=>$visible,
				'linkOptions'=>array('title'=>'Cancel'),
			);
		}

		if ($this->status == self::STATUS_APPROVED_SUPERVISOR) {
			$label = "Consent $name";
			if ($toolbar) {
				$label = "<img src=\"$tool/hand-shake.png\" />";
			}
			$visible = $action != 'consent' &&
				$user->checkAccess('Leave.Consent');
			$menu[] = array(
				'label'=>$label,
				'url'=>array('consent', 'id'=>$this->id),
				'visible'=>$visible,
				'linkOptions'=>array('title'=>'Consent'),
			);

			$label = "Negate $name";
			if ($toolbar) {
				$label = "<img src=\"$tool/hand-finger.png\" />";
			}
			$visible = $action != 'negate' &&
				$user->checkAccess('Leave.Negate');
			$menu[] = array(
				'label'=>$label,
				'url'=>array('negate', 'id'=>$this->id),
				'visible'=>$visible,
				'linkOptions'=>array('title'=>'Negate'),
			);
		}

		return $menu;
	}

}